/**
 * 
 */
package com.iwords.web.base;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.JSONObject;

import com.iwords.service.object.UserEntity;

/**
 * @author BOLIN.HBC
 * @time 2011-3-19
 * @description 所有Action的基类
 */
public abstract class BaseAjaxAction extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected final Log log = LogFactory.getLog(this.getClass());

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			doProcess(req, resp);
		} catch (JSONException e) {
			log.error("JASON ERROR", e);
		}

	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			doProcess(req, resp);
		} catch (JSONException e) {
			log.error("JASON ERROR", e);
		}

	}

	public abstract void doProcess(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException;


	public void jsonPrint(HttpServletResponse res, JSONObject jsobObject) throws IOException, JSONException {

		res.getWriter().print(jsobObject.toString());
		res.getWriter().flush();
	}

	public void forward(HttpServletRequest req, HttpServletResponse resp, String target) {
		ServletContext sc = getServletContext();
		RequestDispatcher rd = null;
		rd = sc.getRequestDispatcher("/" + target); // 定向的页面
		try {
			rd.forward(req, resp);
		} catch (Exception e) {
			this.log.error("forward error", e);
		}
	}

	public void sendRedirect(HttpServletResponse resp, String target, String error) {
		try {
			if (error != null && error.length() > 0) {
				target = target + "?errorMsg=" + error;
			}
			resp.sendRedirect(target);
		} catch (IOException e) {
			this.log.error("sendRedirect error", e);

		}
	}

	public Long getUserId(HttpServletRequest req) {
		Object o = req.getSession().getAttribute("user");
		if (o != null) {
			UserEntity user = (UserEntity) o;
			return user.getUserid();
		}

		// mock 一下
		return 2L;
	}

	public void removeUser(HttpServletRequest req) {
		req.getSession().removeAttribute("user");
		Cookie c[] = req.getCookies();
		c = null;
	}

}
